package com.ruoyi.web.controller.pc.points;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.page.PageUtils;
import com.ruoyi.common.validator.group.AddGroup;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.vo.QueryVo;
import com.ruoyi.web.mapper.PoiApplyImageMapper;
import com.ruoyi.web.mapper.PoiApplyItemMapper;
import com.ruoyi.web.mapper.PoiApplyMapper;
import com.ruoyi.web.mapper.UcQuoTableMapper;
import com.ruoyi.web.service.IPoiApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/points/poiApply")
public class PoiApplyController extends BaseController {

    @Autowired
    private IPoiApplyService poiApplyService;

    @Autowired
    private PoiApplyMapper poiApplyMapper;

    @Autowired
    private UcQuoTableMapper ucQuoTableMapper;

    @Autowired
    private PoiApplyImageMapper poiApplyImageMapper;

    @Autowired
    private PoiApplyItemMapper poiApplyItemMapper;


    @PreAuthorize("@ss.hasPermi('points:poiApply:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryVo queryVo) {
        queryVo.setQStatus(100);
        Long userId = SecurityUtils.getUserId();
        if(userId!=1L){
            queryVo.setQUserId(userId);
        }
        PageUtils page = poiApplyService.listByPage(queryVo);
        return getDataTable(page);
    }

    @PreAuthorize("@ss.hasPermi('points:poiApply:add')")
    @PostMapping("/saveTry")
    public AjaxResult saveTry(@RequestBody PoiApply poiApply) {
        poiApplyService.saveTry(poiApply);
        return toAjax(1);
    }

    @PreAuthorize("@ss.hasPermi('points:poiApply:add')")
    @Log(title = "积分申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated(AddGroup.class) @RequestBody PoiApply poiApply){
        poiApplyService.insert(poiApply);
        return toAjax(1);
    }


    @RequestMapping("/searchApply/{applyId}")
    public AjaxResult searchApply(@PathVariable("applyId") Long applyId){

        Date date =new Date();
        SysUser user = SecurityUtils.getLoginUser().getUser();

        PoiApply poiApply = new PoiApply();
        if(applyId != null && applyId != 0L){

            QueryVo queryVo = new QueryVo();
            queryVo.setQId(applyId);
            poiApply = poiApplyMapper.selectByApply(queryVo);

            queryVo = new QueryVo();
            queryVo.setQId(poiApply.getTableId());
            queryVo.setQFrom(10);
            UcQuoTable ucQuoTable = ucQuoTableMapper.searchBayId(queryVo);
            poiApply.setUcQuoProjects(ucQuoTable.getUcQuoProjectList());

            /*Map<Long,PoiApplyItem> poiApplyItemMap = new HashMap<>();
            for (PoiApplyItem poiApplyItem : poiApply.getPoiApplyItemList()) {
                poiApplyItemMap.put(poiApplyItem.getItemId(),poiApplyItem);
            }
            poiApply.setPoiApplyItemMap(poiApplyItemMap);*/

            for (UcQuoProject ucQuoProject : poiApply.getUcQuoProjects()) {
                for (UcQuoProjectItem ucQuoProjectItem : ucQuoProject.getUcQuoProjectItems()) {

                    Integer numCanApply = 999;
                    LambdaQueryWrapper<PoiApplyItem> lqwPoiApplyItem = new LambdaQueryWrapper<>();
                    lqwPoiApplyItem.eq(PoiApplyItem::getItemId,ucQuoProjectItem.getId());
                    lqwPoiApplyItem.eq(PoiApplyItem::getUserId,user.getUserId());
                    if(ucQuoProjectItem.getLimitType() >=20){
                        numCanApply = ucQuoProjectItem.getLimitMax();
                        lqwPoiApplyItem.eq(PoiApplyItem::getYear,poiApply.getYear());
                    }
                    if(ucQuoProjectItem.getLimitType() >=30){
                        lqwPoiApplyItem.eq(PoiApplyItem::getQuarter,poiApply.getQuarter());
                    }
                    if(ucQuoProjectItem.getLimitType() >=40){
                        lqwPoiApplyItem.eq(PoiApplyItem::getMonth,poiApply.getMonth());
                    }
                    int numApply = poiApplyItemMapper.selectList(lqwPoiApplyItem).stream().mapToInt(PoiApplyItem::getNum).sum();

                    PoiApplyItem poiApplyItem = poiApply.getPoiApplyItemList().stream().filter(item -> {
                        return item.getItemId().equals(ucQuoProjectItem.getId());
                    }).findFirst().orElse(null);

                    if(poiApplyItem!=null){
                        ucQuoProjectItem.setNum(poiApplyItem.getNum());
                        ucQuoProjectItem.setScoreText(poiApplyItem.getScore());
                        ucQuoProjectItem.setContent(poiApplyItem.getContent());
                        ucQuoProjectItem.setNumCanApply(numCanApply - numApply + ucQuoProjectItem.getNum());
                    }else{
                        ucQuoProjectItem.setNumCanApply(numCanApply - numApply);
                    }

                }
            }


            QueryWrapper<PoiApplyImage> qwPoiApplyImage=new QueryWrapper<>();
            qwPoiApplyImage.eq("apply_id",poiApply.getId());
            List<PoiApplyImage> poiApplyImageList = poiApplyImageMapper.selectList(qwPoiApplyImage);

            if(!StringUtils.isEmpty(poiApplyImageList)){
                poiApply.setImgList(new ArrayList<>());
                for (PoiApplyImage poiApplyImage : poiApplyImageList) {
                    poiApply.getImgList().add(poiApplyImage.getImage());
                }
            }

        }else{

            poiApply.setTimeStart(date);
            poiApply.setYear(DateUtils.getYear(date));
            poiApply.setQuarter(DateUtils.getQuarter(date));
            poiApply.setMonth(DateUtils.getMonth(date));

            QueryWrapper<UcQuoTable> qwUcQuoTable = new QueryWrapper<>();
            qwUcQuoTable.eq("is_used",1);
            UcQuoTable ucQuoTableTemp = ucQuoTableMapper.selectOne(qwUcQuoTable);
            QueryVo queryVo = new QueryVo();
            queryVo.setQId(ucQuoTableTemp.getId());
            queryVo.setQFrom(10);
            UcQuoTable ucQuoTable = ucQuoTableMapper.searchBayId(queryVo);
            poiApply.setTableId(ucQuoTable.getId());
            poiApply.setTableName(ucQuoTable.getName());
            poiApply.setUcQuoProjects(ucQuoTable.getUcQuoProjectList());


            for (UcQuoProject ucQuoProject : poiApply.getUcQuoProjects()) {
                for (UcQuoProjectItem ucQuoProjectItem : ucQuoProject.getUcQuoProjectItems()) {

                    Integer numCanApply = 999;
                    LambdaQueryWrapper<PoiApplyItem> lqwPoiApplyItem = new LambdaQueryWrapper<>();
                    lqwPoiApplyItem.eq(PoiApplyItem::getItemId,ucQuoProjectItem.getId());
                    lqwPoiApplyItem.eq(PoiApplyItem::getUserId,user.getUserId());
                    if(ucQuoProjectItem.getLimitType() >=20){
                        numCanApply = ucQuoProjectItem.getLimitMax();
                        lqwPoiApplyItem.eq(PoiApplyItem::getYear,poiApply.getYear());
                    }
                    if(ucQuoProjectItem.getLimitType() >=30){
                        lqwPoiApplyItem.eq(PoiApplyItem::getQuarter,poiApply.getQuarter());
                    }
                    if(ucQuoProjectItem.getLimitType() >=40){
                        lqwPoiApplyItem.eq(PoiApplyItem::getMonth,poiApply.getMonth());
                    }
                    int numApply = poiApplyItemMapper.selectList(lqwPoiApplyItem).stream().mapToInt(PoiApplyItem::getNum).sum();

                    ucQuoProjectItem.setNumCanApply(numCanApply - numApply);

                }
            }

        }


        return success(poiApply);
    }

    @PreAuthorize("@ss.hasPermi('assess:apply:remove')")
    @Log(title = "积分申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{id}")
    public AjaxResult remove(@PathVariable("id") List<Long> ids){
        return toAjax(poiApplyService.delete(ids));
    }

}

